angular.module("module.goodsOrder",[])
    .config(['$stateProvider',function ($stateProvider) {
        $stateProvider
            .state('home.goodsOrder',{
                url:"/goodsOrder",
                templateUrl:"goodsOrder/goodsOrder.html",
                controller:'GoodsOrderController',
                controllerAs:'vm'
            })
    }])
    .controller('GoodsOrderController',[function () {
        var vm=this;
        // var tableList=${tableList};
        console.log("tableList",tableList);
        if(pathname!="/store/goodsOrder"){
            window.location.pathname="/goodsOrder";
        }
        var searchArray=window.location.search.slice(1).split("&");
        for (var i=0;i<searchArray.length;i++){
            searchArray[i]=searchArray[i].split("=");
            data[searchArray[i][0]]=searchArray[i][1];
        }

        console.log("data",data);


        //实现标签页功能
        $('.gn_tabs a').click(function(e) {
            e.preventDefault();
            //    这里调用了boostrap的tap(),实现了标签页的功能呢;
            $(this).tab('show');
            //  实际上这里就是拿到了a标签的hash属性，并做了一次替换
            var tmpl = e.target.hash.replace('#','');
            //  为活动的列表模块设置page和query属性
            $('#'+tmpl).attr('page', 1).attr('query', '');
            loadpage(tmpl);
        });

        //更新页面数据
        function loadpage(tmpl, extend){
            var tmplObj = $('#'+tmpl);
            //    console.log("tmplObj",tmplObj);
            var url = tmplObj.attr('url') || '', page = tmplObj.attr('page') || 1, query = tmplObj.attr('query') || '',roomId=tmplObj.data('orderRoomId');
            //    shopId是从header部分拿到的；
            //    console.log("shopId=",shopId);
            url += '?pi='+page+'&shopId='+shopId+'&'+query;
            //    console.log('roomId',roomId);
            if(roomId)url+='&roomId='+roomId;

            if(data.appId=="wx6a5c075ce0f090da"||data.appId=="wxbe522a217c7da437"){
                url+='&ps=1000';
            }

            $.getJSON(url, function(res){
                if (!res.succeed) return toast('获取数据失败，失败原因：'+res.message);
                data = res.data?$.extend(data,res.data):data;
                //        console.log(url,data);

                //        如果有传入orderNo参数，就唤起弹窗
                if(data.orderNo){
                    (function(data){
                        var orderNo=data.orderNo;
                        console.log("orderNo=",orderNo);
                        console.log("data",data);
                        var vo = {};
                        for (var i=0;i<data.dataList.length;i++){
                            if (data.dataList[i].orderNo==orderNo){
                                vo = data.dataList[i];
                            }
                        }
                        if (!vo) return;
                        $.getJSON('orderGoodsList?orderNo='+orderNo+'&status='+0, function (rs) {
                            if (!rs.succeed) return toast('获取数据失败，失败原因：'+rs.message);
                            rs.data = rs.data || {};
                            rs.data.edit = !!"";
                            rs.data.payType = vo.payType;
                            //            console.log("orderGoodsList_rs.data",rs.data);
                            for (var i =0 ;i<rs.data.list.length;i++) {
                                if (rs.data.list[i].units=='斤'){
                                    rs.data.list[i].goodsCount/=500;
                                }
                            }
                            winAlert({
                                body:template('order_goods_tmpl', rs.data),
                                title:'订单商品列表-包厢'+vo.roomId,
                                cancel: rs.data.edit ? '取消' : false,
                                //——————确定按钮的执行函数——————————————————————————————————————————————————
                                fun:function(){
                                    window.location.href=""
                                }
                                //—————————————————————————————————————————————————————————————————
                            });
                        });
                    })(data);
                }

                //        设置优惠分类列表
                data.discountGoodsTypeList=data[shopId+"goodsTypeList"];
                for (var i=0;i<data.discountGoodsTypeList.length;i++){
                    if (Object.prototype.toString.call(data.discountGoodsTypeList[i].discountLimit)=="[object String]"){
                        data.discountGoodsTypeList[i].discountLimit=data.discountGoodsTypeList[i].discountLimit.split(",")
                    }
                }

                //      如果当前页码超过最大页数，跳回最后一页
                if (data.totalPage>0 && data.totalPage<page){
                    tmplObj.attr('page',data.totalPage);
                    return loadpage(tmpl, extend);
                }

                //        $extend将后面的对象属性添加到前一个属性中去，如果有冲突就保留后一个对象的值
                data = $.extend(data, extend);
                data.status = tmpl;
                for (var i=0;i<data.dataList.length;i++){
                    data.dataList[i].ctime2=data.dataList[i].ctime.split(" ")
                }

                //        如果是中兴瑞恒或者久久江记就构造桌台列表对象
                if (data.dataList&&(data.appId=="wx6a5c075ce0f090da"||data.appId=="wxbe522a217c7da437")){
                    data.tableList=tableList.tableList;
                    data.tableList.maxStid=0;
                    for (var j=0;j<data.tableList.length;j++){
                        data.tableList[j].orderList=[];
                        data.tableList[j].totalMoney=0;
                        if (data.tableList.maxStid<data.tableList[j].stid){
                            data.tableList.maxStid=data.tableList[j].stid;
                        }
                        for(var i=0;i<data.dataList.length;i++){
                            var roomId=data.dataList[i].roomId;
                            if (data.tableList[j].stid==roomId){
                                data.tableList[j].orderList.push(data.dataList[i]);
                                data.tableList[j].totalMoney+=data.dataList[i].totalMoney;
                            }
                        }
                    }
                }
                console.log("before_order_tmpl",data);
                tmplObj.html(template('order_tmpl', data));
                var pArray=$("[name=desk_editor_p]");
                pArray.hide();

                //        console.log("before_module_function_set",data);
                module_function_set(data, tmpl, tmplObj);
            });

            $("#search_a").off().on("click",function (e) {
                //        console.log(e);
                e.preventDefault();
                var orderRoomId=$("#searchStr").val();
                //            console.log("goodsNameContent",goodsNameContent);
                //    这里调用了boostrap的tap(),实现了标签页的功能呢;
                var tmpl = $('div.active').eq(0).attr("id");
                $("#"+tmpl).data("orderRoomId",orderRoomId);
                $("#"+tmpl).attr('page',1);
                //        console.log($("#"+tmpl));
                loadpage(tmpl);
            });

        }

        //实现页码跳转页面功能
        function topage(tmpl, data){
            $('.tab-pane.active .pagination a').on('click', function(){
                $('.tab-pane.active').attr('page', $(this).attr('href'));
                loadpage(tmpl, data);
                return false;
            });
        }

        //为订单列表模块所有按钮附上功能
        function module_function_set(data, tmpl, tmplObj){

            var pArray=$("[name=desk_editor_p]");
            //        当点击桌台按钮的时候显示每个桌台下面的编辑按钮
            $("#desk_editor_control").off().on('click',function () {
                pArray.toggle();
            });

            //        为点击桌台附上功能
            $('[name="table"]').off().on('click',function (e) {
                e.preventDefault();
                var roomId=parseInt($(this).data("tableId"));
                for (var i=0;i<data.tableList.length;i++){
                    if(data.tableList[i].stid==roomId){
                        var orderList=data.tableList[i].orderList;
                    }
                }
                var isSimpleShop=(shopList.shopList.length==1);
                console.log("isSimpleShop",isSimpleShop);
                //            console.log("orderList",orderList);
                if (orderList.length<1&&tmpl=="receive"&&isSimpleShop){
                    window.location.href="orderCreate?roomId="+roomId;
                }else if(orderList.length>=1){
                    console.log("orderList",orderList);
                    winAlert({
                        body:template('table_order_tmpl',{orderList:orderList,status:tmpl}),
                        title:'包厢订单列表-包厢'+roomId,
                        cancel:  '取消',
                        //——————确定按钮的执行函数
                        fun:function(){
                            $(".close").trigger("click");
                            loadpage(tmpl);
                        }
                    });

                }
                //            console.log("data");
                module_function_set(data,tmpl,tmplObj)
            });

            //        实现编辑桌台功能
            $("[name=desk_editor]").off().on('click',function () {
                var stid=$(this).data("tableId");
                console.log("stid",stid);
                var table={};
                var tableArray=tableList.tableList;
                var index;
                console.log("tableArray=",tableArray);
                for (var i=0;i<tableArray.length;i++){
                    if(stid==tableArray[i].stid){
                        table=tableArray[i];
                        index=i;
                    }
                }
                console.log("table=",table);
                winAlert({
                    body:template('desk_editor_tmpl',table),
                    title:'包厢信息编辑',
                    btn:"保存",
                    cancel:'删除',
                    //——————确定按钮的执行函数
                    fun:function(){
                        console.log(table);
                        $.getJSON("/store/updateTable",table,function (res) {
                            if (res.succeed){
                                res.data=JSON.stringify(res.data.jsonString);
                                toast("修改桌台信息成功，重新加载页面中","success",function () {
                                    console.log("updateTable",res);
                                    console.log("data.tableList",data.tableList);
                                    tmplObj.html(template('order_tmpl', data));
                                    module_function_set(data, tmpl, tmplObj);
                                });
                            }else {
                                toast("修改桌台信息失败，失败原因"+res.message);
                                console.log("deleteTable",res)
                            }
                            console.log("updateTable",res)
                        });
                        $(".close").trigger("click");
                    },
                    cancelFun:function () {
                        console.log(table);
                        $.getJSON("/store/deleteTable",table,function (res) {
                            if (res.succeed){
                                res.data=JSON.stringify(res.data.jsonString);
                                toast("删除桌台成功，重新加载页面中","success",function () {
                                    console.log("deleteTable",res);
                                    data.tableList.splice(index,1);
                                    console.log("data.tableList",data.tableList);
                                    tmplObj.html(template('order_tmpl', data));
                                    module_function_set(data, tmpl, tmplObj);
                                });
                            }else {
                                toast("修改桌台信息失败，失败原因"+res.message)
                                console.log("deleteTable",res)
                            }
                        });
                        $(".close").trigger("click");
                    }
                });

                $("#stname").off().on("change",function () {
                    table.stname=$(this).val()
                })

            });

            //    实现添加桌台功能
            $("#add_table").off().on('click',function () {
                var tableArray=tableList.tableList;
                var table={};
                $.extend(true,table,tableArray[tableArray.length-1]);
                table.stid=tableArray.maxStid+1;
                table.stname="";
                winAlert({
                    body:template('desk_editor_tmpl',table),
                    title:'新增包厢编辑',
                    btn:"保存",
                    //——————确定按钮的执行函数
                    fun:function(){
                        console.log(table);
                        $.getJSON("/store/addTable",table,function (res) {
                            if (res.succeed){
                                tableArray.maxStid++;
                                res.data=JSON.stringify(res.data.jsonString);
                                toast("添加桌台信息成功，重新加载页面中","success",function () {
                                    console.log("addTable",res);
                                    data.tableList.push(table);
                                    console.log("data.tableList",data.tableList);
                                    var display=$("[name=desk_editor_p]").eq(0).css('display');
                                    console.log("display",display);
                                    tmplObj.html(template('order_tmpl', data));
                                    console.log("display",display);
                                    $("[name=desk_editor_p]").css("display",display);
                                    module_function_set(data, tmpl, tmplObj);
                                });
                            }else {
                                toast("修改桌台信息失败，失败原因"+res.message);
                                console.log("addTable",res)
                            }
                        });
                        $(".close").trigger("click");
                    }
                });

                $("#stname").off().on("change",function () {
                    table.stname=$(this).val()
                })
            });

            //实现退单功能(退单浮框及退单浮框系列功能)
            $('.chakan').off().on('click', function(){
                var i = $(this).attr('data-i');
                var orderNo = $(this).attr('data-orderNo');
                console.log("orderNo",orderNo);
                var type = $(this).attr('data-type') || '';
                var vo = {};
                for (var i=0;i<data.dataList.length;i++){
                    if (data.dataList[i].orderNo==orderNo){
                        vo = data.dataList[i];
                    }
                }
                var tm = {receive:0, complete:1, refuseList:2, orderSearch:3};
                if (!vo) return;
                $.getJSON('orderGoodsList?orderNo='+vo.orderNo+'&status='+tm[tmpl], function (rs) {
                    if (!rs.succeed) return toast('获取数据失败，失败原因：'+rs.message);
                    rs.data = rs.data || {};
                    rs.data.edit = !!type;
                    rs.data.payType = vo.payType;
                    //            console.log("orderGoodsList_rs.data",rs.data);
                    for (var i =0 ;i<rs.data.list.length;i++) {
                        if (rs.data.list[i].units=='斤'){
                            rs.data.list[i].goodsCount/=500;
                        }
                    }
                    winAlert({body:template('order_goods_tmpl', rs.data),title:'订单商品列表-包厢'+vo.roomId, cancel: rs.data.edit ? '取消' : false,
                        //——————确定按钮的执行函数
                        fun:function(){
                            if (!rs.data.edit) return true;
                            var checkObj = $('.winAlert :input[name="goodsId"]:checked');
                            if (checkObj.length<1) return toast('请选择要退的商品');
                            var refundList=[];
                            $.each(checkObj, function(){
                                var beforeTd=$(this).parent().prev();
                                var input=beforeTd.find("input");
                                var data={
                                    id:$(this).val(),
                                    unsubscribeNum:input.val(),  //该商品退订量
                                    count:input.data('max'),
                                    units:input.data("units")
                                };
                                console.log(data);
                                refundList.push(data);
                            });
                            console.log("refundList=",refundList);
                            console.log("JSON.stringify(refundList)",JSON.stringify(refundList));
                            var judgmentCondition=true;
                            if(refundList.length<rs.data.list.length){
                                judgmentCondition=false
                            }else {
                                for(var i in refundList){
                                    if(refundList[i].count!=refundList[i].unsubscribeNum) {
                                        judgmentCondition=false;
                                        break;
                                    }
                                }
                            }
                            return $.getJSON(/*data.appId=='wxa46d90e859cc17a5'?'refundOrder':*/'refundOrder',
                                {
                                    orderNo:vo.orderNo,
                                    refundList:judgmentCondition?'':JSON.stringify(refundList),
                                    message:$('#refundReason').val(),
                                    shopId:shopId //shopId来自header.html
                                },
                                function(rs){
                                    if (!rs.succeed) return toast('获取数据失败，失败原因：'+rs.message);
                                    toast('退货成功...', 'success');
                                    loadpage(tmpl);
                                    return true;
                                });
                        }});

                    //——————————————————————————————————————————————————————————————————

                    //——————实现点击后加减按钮的显示和消失，以及退订数的变化
                    $(":checkbox").click(function () {
                        var beforeTd=$(this).parent().prev();
                        var input=beforeTd.find("input");
                        var btn=beforeTd.find("span");
//                    console.log("$(this)",$(this));
//                    console.log("beforeTd",beforeTd);
//                    console.log("input",input,"btn",btn);
                        if(this.checked){
                            btn.show();
                            input.attr("disabled",false);
                            input.val(input.data("max"));
                        }else {
                            btn.hide();
                            input.attr("disabled",true);
                            input.val(0);
                        }
                    });
                    //——————————————————————————————————————————————————————————————————
                    $('.glyphicon').hide();

                    //——————实现全选
                    $(".winAlert .checkAll").on("click", function(){
                        var inputList=$('.winAlert :input[name=goodsId]');
                        for (var i =0;i< inputList.length;i++){
                            //                    console.log(inputList[i]);
                            if(inputList[i].checked==false){
                                var searchString="[value="+inputList[i].value+"]";
                                //                        console.log(inputList[i].value);
                                $(searchString).trigger("click")
                            }
                        }
                    });
                    //——————————————————————————————————————————————————————————————————

                    //——————实现全不选
                    $('.winAlert .inverse').on('click', function(){
                        var inputList=$('.winAlert :input[name=goodsId]');
                        for (var i =0;i< inputList.length;i++){
                            //                    console.log(inputList[i]);
                            if(inputList[i].checked==true){
                                var searchString="[value="+inputList[i].value+"]";
                                //                        console.log(inputList[i].value);
                                $(searchString).trigger("click")
                            }
                        }
                    });
                    //——————————————————————————————————————————————————————————————————

                    //——————实现加减按钮————————————————————————————————————————————————————
                    $('span.glyphicon-plus').click(function () {
                        var searchString="input#"+$(this).attr("name");
                        console.log($("#20"));
//                    console.log($(searchString).data("max"));
                        if (parseInt($(searchString).val())<$(searchString).data("max")){
                            $(searchString).val(parseInt($(searchString).val())+1);
                        }
                    });

                    $('span.glyphicon-minus').click(function () {
                        var searchString="input#"+$(this).attr("name");
//                    console.log($(searchString).val());
                        if (parseInt($(searchString).val())>1){
                            $(searchString).val(parseInt($(searchString).val())-1);
                        }
                    })
                    //————————————————————————————————————————————————————————————————————
                });
            });

            //    为打印按钮添加功能(确认打印弹窗)—————————————————————————————————————————————————
            $('.print').off().on('click', function(){
                var i = $(this).attr('data-i');
                var orderNo = $(this).attr('data-orderNo');
                console.log("orderNo",orderNo)
                var vo = {};
                for (var i=0;i<data.dataList.length;i++){
                    if (data.dataList[i].orderNo==orderNo){
                        vo = data.dataList[i];
                    }
                }
                winAlert({body:'您确定要重新打印订单么',cancel:'取消',fun:function(){
                    return $.getJSON('printAgain', {id:vo.id}, function(rs){
                        if (!rs.succeed) return toast('打印失败，失败原因：'+rs.message);
                        toast('打印成功...', 'success');
                    });
                }});
            });

            //    为支付按钮添加支付功能(确认支付弹窗)—————————————————————————————————————————————————
            $('.payment').off().on('click', function(){
                //        console.log("data",data);
                var i = $(this).attr('data-i');
                var orderNo = $(this).attr('data-orderNo');
                console.log("orderNo",orderNo)
                var vo = {};
                for (var i=0;i<data.dataList.length;i++){
                    if (data.dataList[i].orderNo==orderNo){
                        vo = data.dataList[i];
                    }
                }
                var goodsTypeList=[];
                //        console.log("data.dataList[i]",data.dataList[i]);
                $.getJSON('orderGoodsList',{orderNo:vo.orderNo},function (res) {
                    var goodsList=res.data.list;
                    console.log(vo.orderNo,"goodsList:",res.data.list);
                    vo.memberPrice=0;vo.commonPrice=0;
                    // 计算订单总价
                    function Calculate_totalMoney(goodsTypeList) {
                        var goodsTypeList=goodsTypeList||[];
                        //            console.log("C_goodsTypeList",goodsTypeList);
                        vo.memberPrice=0;
                        vo.commonPrice=0;
                        for (var i=0;i<goodsList.length;i++){
                            var goodsItem = goodsList[i];
                            var goodsMemberPrice=goodsItem.goodsMemberPrice;
                            var goodsCommonPrice=goodsItem.goodsCommonPrice;
                            var goodsCount=goodsItem.goodsCount;
                            var units=goodsItem.units;
                            var discountLimit=1;
                            for (var j=0;j<goodsTypeList.length;j++){
                                var id=goodsTypeList[j].id;
                                //                    console.log("typeId",id,"goodsTypeId",goodsItem.goodsTypeId);
                                if (goodsItem.goodsTypeId==id){
                                    discountLimit=goodsTypeList[j].discountLimit/10;
                                }
                            }
                            //                console.log(goodsItem.goodsName,discountLimit);
                            if (units=='斤') {
                                vo.memberPrice+=goodsMemberPrice*discountLimit*goodsCount/500;
                                vo.commonPrice+=goodsCommonPrice*discountLimit*goodsCount/500;
                            } else {
                                vo.memberPrice+=goodsMemberPrice*discountLimit*goodsCount;
                                vo.commonPrice+=goodsCommonPrice*discountLimit*goodsCount;
                            }
                        }
                    }
                    //          计算订单总价结束
                    //            console.log(681);
                    Calculate_totalMoney();
                    vo.discountGoodsTypeList=[];

                    for(var i=0;i<data.discountGoodsTypeList.length;i++){
                        if (data.discountGoodsTypeList[i].discountStatus==true){
                            for (var j=0;j<goodsList.length;j++){
                                if (goodsList[j].goodsTypeId==data.discountGoodsTypeList[i].id){
                                    vo.discountGoodsTypeList.push(data.discountGoodsTypeList[i]);
                                    break;
                                }
                            }
                        }
                    }

                    vo.allDiscountList=[];

                    for (var i =0;i<vo.discountGoodsTypeList.length;i++){
                        var discountLimit=vo.discountGoodsTypeList[i].discountLimit;
                        discountLimit=discountLimit.sort();
                        for(var j=0;j<discountLimit.length;j++){
                            var boolean=true;
                            for (var k=0;k<vo.allDiscountList.length;k++){
                                if(vo.allDiscountList[k]==discountLimit[j]){
                                    boolean=false;
                                    break;
                                }
                            }
                            if (boolean){
                                vo.allDiscountList.push(discountLimit[j])
                            }
                        }
                    }

                    vo.allDiscountList=vo.allDiscountList.sort();

                    winAlert({title:'支付页面',body:template('discount_tmpl',vo),cancel:'取消',fun:function(){
                        $(".close").trigger("click");
                    }});

                    //给单个类的打折的CheckBox附上功能
                    $("[name=singleDiscountLimit]").find(":input").off().on("click",function () {
                        var boolean=true;
                        for (var i=0;i<goodsTypeList.length;i++){
                            if (goodsTypeList[i].id==$(this).data("goodsTypeId")){
                                goodsTypeList[i].discountLimit=$(this).val();
                                boolean=false
                            }
                        }
                        if (boolean){
                            goodsTypeList.push({id:$(this).data("goodsTypeId"),discountLimit:$(this).val()})
                        }
                        Calculate_totalMoney(goodsTypeList);

                        var memberMoney=vo.memberPrice;
                        var totalMoney= vo.commonPrice;
                        var coupon=$("#coupon").val();
                        var discount=$("#discount").val();

                        if(totalMoney-coupon>0){
                            totalMoney-=coupon;
                            if (totalMoney-discount>0){
                                totalMoney-=discount;
                            }else {
                                $("#discount").val(0);
                                toast("优惠券和抹零总和不能大于商品总价")
                            }
                        } else{
                            $("#coupon").val(0);
                            $("#discount").val(0);
                            toast("优惠券和抹零总和不能大于商品总价")
                        }

                        if(memberMoney-coupon>0){
                            memberMoney-=coupon;
                            if (memberMoney-discount>0){
                                memberMoney-=discount;
                            }else {
                                memberMoney=0;
                            }
                        } else{
                            memberMoney=0;
                        }

                        $("#memberpay").val((memberMoney/100).toFixed(2));
                        $("#pay").val((totalMoney/100).toFixed(2));
                    });

                    //给全单打折的CheckBox附上功能
                    $("[name=AllDiscountLimit]").off().on("click",function () {
                        var val=parseFloat($(this).val());
                        var inputArray=[];
                        for (var i=0;i<$("[name=singleDiscountLimit]").length;i++){
                            inputArray[i]=[];
                            for(var j = 0;j<$("[name=singleDiscountLimit]").eq(i).find(":input").length;j++){
                                inputArray[i].push($("[name=singleDiscountLimit]").eq(i).find(":input").eq(j));
                            }
                        }

                        for (var i= 0;i<inputArray.length;i++){
                            for(var j =0 ;j<inputArray[i].length;j++){
                                if (parseFloat(inputArray[i][j].val())>=val){
                                    inputArray[i][j].trigger("click");
                                    break;
                                }
                            }
                        }
                    });

                    //保证优惠券输入框始终有值，保证优惠券及抹零总和小于商品总价，并让应付保持正确
                    $("#coupon").off().on({"blur":function () {
                        var coupon=$("#coupon").val();
                        var discount=$("#discount").val();

                        if (coupon==""||coupon==null){
                            $("#coupon").val(0);
                            coupon=$("#coupon").val();
                        }

                        if (discount==""||discount==null){
                            $("#discount").val(0);
                            discount=$("#discount").val();
                        }

                        console.log("coupon:",coupon," discount:",discount)
                        if ($("#totalMoney").val()*100<coupon*100+discount*100){
                            $("#coupon").val(0);
                            return toast("优惠券和抹零总和不能大于商品总价")
                        }
                        var pay=($("#totalMoney").val()-coupon-discount)*100;
                        $("#pay").val((pay/100).toFixed(2));

                        if ($("#memberMoney").val()*100<coupon*100+discount*100){
                            $("#memberpay").val(0);
                        }else {
                            var memberpay=($("#memberMoney").val()-coupon-discount)*100;
                            $("#memberpay").val((memberpay/100).toFixed(2))
                        }
                    },
                        "focus":function () {
                            if ($("#coupon").val()==0) $("#coupon").val("");
                        }
                    });

                    //保证抹零输入框始终有值，保证优惠券及抹零总和小于商品总价，并让应付保持正确
                    $("#discount").off().on({
                        "blur":function () {
                            var coupon=$("#coupon").val();
                            var discount=$("#discount").val();

                            if (coupon==""||coupon==null){
                                $("#coupon").val(0);
                                coupon=$("#coupon").val();
                            }

                            if (discount==""||discount==null){
                                $("#discount").val(0);
                                discount=$("#discount").val();
                            }

                            console.log("coupon:",coupon," discount:",discount);

                            if ($("#totalMoney").val()*100<coupon*100+discount*100){
                                $("#discount").val(0);
                                return toast("优惠券和抹零总和不能大于商品总价")
                            }
                            if (discount>10){
                                $("#discount").val(0);
                                return toast("抹零不能大于10元")
                            }
                            var pay=($("#totalMoney").val()-coupon-discount)*100;
                            $("#pay").val((pay/100).toFixed(2));

                            if ($("#memberMoney").val()*100<coupon*100+discount*100){
                                $("#memberpay").val(0);
                            }else {
                                var memberpay=($("#memberMoney").val()-coupon-discount)*100;
                                $("#memberpay").val((memberpay/100).toFixed(2))
                            }
                        },
                        "focus":function () {
                            if ($("#discount").val()==0) $("#discount").val("");
                        }
                    });

                    //点击桌台的时候修改订单优惠状态，并唤起二维码弹窗-------------------------------------------------------------------------
                    $("#table").off().on("click",function () {
                        var isMember=$("#isMember").is(":checked");
                        var para={
                            coupon:$("#coupon").val()*100,
                            discount:$("#discount").val()*100,
                            totalMoney:(isMember?parseFloat($("#memberpay").val())*100:parseFloat($("#pay").val())*100).toFixed(0),
                            orderNo:vo.orderNo
                        };
                        console.log("para",para);
                        $.post("/store/orderDiscount",para,function (res) {
                            try{res=JSON.parse(res);}catch(e){toast("a"+e);}
                            if (!res.succeed) return toast("b"+res.message);
                            //                    console.log(525,"#table_res",res);
                            var Url="http://www.zxrhw.com/pay/getQuasyOrderPay?appId="+vo.appId+"&shopId="+shopId+"&shopAppId="+vo.appId+"&roomId="+vo.roomId;
                            console.log("Url",Url);
                            winAlert({title:'扫码支付',body:template('QR_code_tmpl'),fun:function(){
                                $(".close").trigger("click");
                                loadpage(tmpl);
                            }});
                            creatCode(Url,"QR_code");
                        })
                    });
                    //----------------------------------------------------------------------------------------------------------------------

                    //点击其他支付的时候修改订单优惠状态，并唤起选择支付方式弹窗-------------------------------------------------------------------
                    $("#other_payments").off().on("click",function () {
                        var isMember=$("#isMember").is(":checked");
                        var para = {
                            coupon: $("#coupon").val() * 100,
                            discount: $("#discount").val() * 100,
                            totalMoney:isMember?(parseFloat($("#memberpay").val())* 100).toFixed(0):(parseFloat($("#pay").val())* 100).toFixed(0),
                            orderNo: vo.orderNo
                        };
                        console.log("para",para);
                        //修改订单状态-----------------------------------------------------------------------------------------------------------
                        $.post("/store/orderDiscount", para, function (res) {
                            try {
                                res = JSON.parse(res);
                            } catch (e) {
                                toast(e);
                            }
                            if (!res.succeed) return toast(res.message);
                            //----------------------------------------------------------------------------------------------------------------------

                            //唤起选择支付方式弹窗---------------------------------------------------------------------------------------------------
                            winAlert({
                                title: '请选择支付方式',
                                body:
                                '<table class="table table-bordered from_table">' +
                                '<tr>' +
                                '<td>' +
                                '<button id="alpay" class="btn btn-info">支付宝</button>' +
                                '</td>' +
                                '<td>' +
                                '<button id="pos" class="btn btn-info">pos</button>' +
                                '</td >' +
                                '<td>' +
                                '<button id="cash" class="btn btn-info">现金</button>' +
                                '</td>' +
                                '</tr>' +
                                '</table>',
                                fun: function () {
                                    $(".close").trigger("click");
                                }
                            });
                            //----------------------------------------------------------------------------------------------------------------------

                            //为选择支付弹窗中的不同支付按钮提供确定支付功能，及确定支付后完成订单------------------------------------------------------
                            $("#alpay").off().on({
                                "click": function () {
                                    winAlert({
                                        title: '支付宝支付',
                                        body: "确认支付完成?",
                                        fun: function () {
                                            console.log(vo.orderNo);
                                            $.getJSON("orderFinish",
                                                {
                                                    orderNo: vo.orderNo,
                                                    payType: 3
                                                },
                                                function (res) {
                                                    if (!res.succeed) return toast('操作失败，失败原因：' + res.message);
                                                    $.getJSON('orderCompletePrint', {orderNo:vo.orderNo},function (res) {
                                                        console.log("orderCompletePrint_res:",res);
                                                        if (!res.succeed) return toast('打单失败，失败原因：' + res.message);
                                                        toast('操作成功,打单中', 'success');
                                                        $(".close").trigger("click");
                                                        loadpage(tmpl);
                                                    })
                                                }
                                            );
                                        }
                                    });
                                }
                            });

                            $("#pos").off().on({
                                "click": function () {
                                    winAlert({
                                        title: 'POS支付',
                                        body: "确认支付完成?",
                                        fun: function () {
                                            console.log(vo.orderNo);
                                            $.getJSON("orderFinish",
                                                {
                                                    orderNo: vo.orderNo,
                                                    payType: 4
                                                },
                                                function (res) {
                                                    if (!res.succeed) return toast('操作失败，失败原因：' + res.message);
                                                    $.getJSON('orderCompletePrint', {orderNo:vo.orderNo},function (res) {
                                                        console.log("orderCompletePrint_res:",res);
                                                        if (!res.succeed) return toast('打单失败，失败原因：' + res.message);
                                                        toast('操作成功,打单中', 'success');
                                                        $(".close").trigger("click");
                                                        loadpage(tmpl);
                                                    })
                                                }
                                            )
                                        }
                                    });
                                }
                            });

                            $("#cash").off().on({
                                "click": function () {
                                    winAlert({
                                        title: '现金支付',
                                        body: "确认支付完成?",
                                        fun: function () {
                                            console.log(vo.orderNo);
                                            $.getJSON("orderFinish",
                                                {
                                                    orderNo: vo.orderNo,
                                                    payType: 5
                                                },
                                                function (res) {
                                                    if (!res.succeed) return toast('操作失败，失败原因：' + res.message);
                                                    $.getJSON('orderCompletePrint', {orderNo:vo.orderNo},function (res) {
                                                        console.log("orderCompletePrint_res:",res);
                                                        if (!res.succeed) return toast('打单失败，失败原因：' + res.message);
                                                        toast('操作成功,打单中', 'success');
                                                        $(".close").trigger("click");
                                                        loadpage(tmpl);
                                                    })
                                                }
                                            )
                                        }
                                    });
                                }
                            });
                            //----------------------------------------------------------------------------------------------------------------------
                        })
                    })
                });
            });
            //————————————————————————————————————————————————————————————————————

            $('.addGoods').off().on('click', function(){
                var i = $(this).attr('data-i');
                var orderNo = $(this).attr('data-orderNo');
                console.log("orderNo",orderNo)
                var vo = {};
                for (var i=0;i<data.dataList.length;i++){
                    if (data.dataList[i].orderNo==orderNo){
                        vo = data.dataList[i];
                    }
                }
                window.location.href="addGoodsView?orderNo="+vo.orderNo+"&roomId="+vo.roomId
            })

            //     为完成按钮添加功能(确认完成弹窗)—————————————————————————————————————————————————
            $('.finish').off().on('click', function(){
                var i = $(this).attr('data-i');
                var orderNo = $(this).attr('data-orderNo');
                console.log("orderNo",orderNo);
                var vo = {};
                for (var i=0;i<data.dataList.length;i++){
                    if (data.dataList[i].orderNo==orderNo){
                        vo = data.dataList[i];
                    }
                }
                winAlert({body:'您确定要确认完成该订单吗？',cancel:'取消',fun:function(){
                    return $.getJSON('orderFinish', {orderNo:vo.orderNo}, function(rs){
                        if (!rs.succeed) return toast('操作失败，失败原因：'+rs.message);
                        $.getJSON('orderCompletePrint', {orderNo:vo.orderNo},function (res) {
                            console.log("orderCompletePrint_res:",res);
                            if (!res.succeed) return toast('打单失败，失败原因：' + res.message);
                            toast('操作成功,打单中', 'success');
                            $(".close").trigger("click");
                            loadpage(tmpl);
                            return true;
                        })
                    });
                }});
            });

            topage(tmpl, tmpl == 'orderSearch'?{startTime:data.startTime, endTime:data.endTime}:{});

            $('.datetime').daterangepicker({format: 'YYYY-MM-DD HH:mm',timePicker:true,
                timePickerSeconds:true,timePickerIncrement:1,timePicker12Hour:false}, function(start, end) {
                data.startTime = start.format('YYYY-MM-DD HH:mm');
                data.endTime = end.format('YYYY-MM-DD HH:mm');
                $(':input[name=startTime]').val(data.startTime);
                $(':input[name=endTime]').val(data.endTime);
            });

            $('.daterang').off().on('click', function(){
                var day = parseInt($(this).attr('data-day'), 10);
                data.startTime = moment().subtract(day, 'days').format('YYYY-MM-DD 00:00');
                data.endTime = moment().format('YYYY-MM-DD HH:mm');
                $(':input[name=startTime]').val(data.startTime);
                $(':input[name=endTime]').val(data.endTime);
                return false;
            });

            if (tmpl == 'orderSearch') {
                $('.search').on('click', function(){
                    var startTime = $(':input[name=startTime]').val();
                    var endTime = $(':input[name=endTime]').val();
                    tmplObj.attr('query','startTime='+encodeURI(startTime)+'&endTime='+encodeURI(endTime));
                    tmplObj.attr('page', 1);
                    loadpage(tmpl, {startTime:startTime, endTime:endTime});
                    return false;
                });
                $('.reset').on('click', function(){
                    tmplObj.attr('query','');tmplObj.attr('page', 1);
                    loadpage(tmpl);
                    return false;
                });
            }
        }

        //生成二维码依赖函数
        function xyqrcode(options) {
            var settings = {
                dom:'',
                render: 'canvas',   //生成二维码的格式还有image、div
                ecLevel:"H",
                text:"www.baidu.com",
                background:"#ffffff",
                fill:"#333333", //二维码纹路的颜色
                fontcolor:"#ff9818",
                fontname:"Ubuntu",
                image:{},
                label:"",
                mPosX:0.5,   //图片在X轴的位置
                mPosY:0.5,    //图片在X轴的位置
                mSize:0.27,   //图片大小
                minVersion:5,
                mode:0,
                quiet:1,
                radius:1,
                size:200
            };
            if (options) {
                $.extend(settings, options);//options对象跟settings比较，相同的就替换，没有的就添加

            }
            if(settings.dom.length==0){
                window.console.log("Error: dom empty!");
                return;
            }
            if(settings.url.length==0){
                window.console.log("Error: url empty!");
                return;
            }
            console.log(settings);
            settings.text=settings.url; //在qrcode生成二维码的地址是text。这里就把url赋值给text
            $(settings.dom).qrcode(settings);
        }

        //生成二维码函数
        function creatCode(url,divId){
            var options={};
            options.url=url; //二维码的链接
            options.dom="#"+divId;//二维码生成的位置
            options.image='';//图片id
            options.render="canvas";//设置生成的二维码是canvas格式，也有image、div格式
            xyqrcode(options);
        }

        loadpage('receive');
    }]);